package com.zj.syzs.fragment;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;

import com.alibaba.fastjson.JSON;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.zj.shouyou.R;
import com.zj.syzs.adapter.ActiveAdapter;
import com.zj.syzs.adapter.ViewPageAdapter;
import com.zj.syzs.bean.ActiveBean;
import com.zj.syzs.bean.Active_AD_Bean;
import com.zj.syzs.config.UrlConfig;
import com.zj.syzs.utils.HttpUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 应用程序配置类
 */
public class ActiveFragment extends Fragment implements PullToRefreshListView.OnRefreshListener2<ListView> {
    private PullToRefreshListView ptrListView;
    private List<ActiveBean> list = new ArrayList<>();
    private ArrayList<Active_AD_Bean> ad_list = new ArrayList<>();
    private ArrayList<View> views = new ArrayList<>();
    private ActiveAdapter adapter;
    private ViewPageAdapter headAdapter;
    private int page = 1;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_active, container, false);
        initView(view, inflater);
        initBanner();
        initData();
        return view;
    }

    private void initView(View view, LayoutInflater inflater) {
        // listview + adapter + 数据源
        ptrListView = (PullToRefreshListView) view.findViewById(R.id.fragment_active_listview);
        ptrListView.setMode(PullToRefreshBase.Mode.BOTH);
        ptrListView.setOnRefreshListener(this);
        ptrListView.setShowIndicator(true);
        adapter = new ActiveAdapter(list, getActivity());
        ptrListView.setRefreshing();
        // 刷新时间
        String label = DateUtils.formatDateTime(getActivity(), System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE
                | DateUtils.FORMAT_ABBREV_ALL);
        // 设置刷新时候的字体
        ptrListView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
        ptrListView.setAdapter(adapter);


        ListView listView = ptrListView.getRefreshableView();
        listView.addHeaderView(getHeadView(inflater));
    }

    private void initData() {
        new LoadGiftTask().execute(UrlConfig.ACTIVE_URL);
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        ILoadingLayout iLoadingLayout = refreshView.getLoadingLayoutProxy();
        String label = DateUtils.formatDateTime(getActivity(), System.currentTimeMillis(),
                DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
        //设置刷新的标签
        iLoadingLayout.setLastUpdatedLabel(label);
        page = 1;
        initBanner();
        initData();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        page++;
        if (page == 2) {
            ptrListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        }
        initData();
    }

    /**
     * 第一步 继承AsyncTask
     * 第二步 重写doInBackground方法
     * Thread + Hanlder
     */
    private class LoadGiftTask extends AsyncTask<String, Void, List<ActiveBean>> {
        @Override
        protected List<ActiveBean> doInBackground(String... params) {
            HashMap<String, String> map = getMap();
            try {
                String jsonResult = HttpUtils.post(params[0], map);
                String state = new JSONObject(jsonResult).optString("state");
                if ("success".equals(state)) {
                    JSONArray arr = new JSONObject(jsonResult).getJSONArray("info");
                    List<ActiveBean> activeBeans = JSON.parseArray(arr.toString(), ActiveBean.class);
                    return activeBeans;
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        private HashMap<String, String> getMap() {
            HashMap<String, String> params = new HashMap<>();
            params.put("uid", "");
            params.put("token", "78fc45f6f%2C7%2C9");
            params.put("platform", "2");
            params.put("gifttype", "1");
            params.put("page", page + "");
            return params;
        }

        //  handler代码
        @Override
        protected void onPostExecute(List<ActiveBean> activeBeans) {
            super.onPostExecute(activeBeans);
            if (activeBeans != null && !activeBeans.isEmpty()) {
                if (page == 1 && !list.isEmpty()) {
                    list.clear();
                }
                list.addAll(activeBeans);
                adapter.notifyDataSetChanged();
                ptrListView.onRefreshComplete();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    //顶部广告栏
    private View getHeadView(LayoutInflater inflater) {
        View head = inflater.inflate(R.layout.headview_active, null);
        ViewPager headViewPager = (ViewPager) head.findViewById(R.id.fragment_active_viewpager);
        headAdapter = new ViewPageAdapter(views);
        headViewPager.setMinimumHeight(120);
        headViewPager.setAdapter(headAdapter);
        return head;
    }


    private void initBanner() {
        new HeadAdTask().execute(UrlConfig.ACTIVE_AD_URL);
    }

    private class HeadAdTask extends AsyncTask<String, Void, List<Active_AD_Bean>> {

        @Override
        protected List<Active_AD_Bean> doInBackground(String... params) {
            HashMap<String, String> map = getparams();
            try {
                String jsonResult = HttpUtils.post(params[0], map);
                String state = new JSONObject(jsonResult).optString("state");
                if ("success".equals(state)) {
                    JSONArray arr = new JSONObject(jsonResult).getJSONArray("info");
                    List<Active_AD_Bean> active_ad_beans = JSON.parseArray(arr.toString(), Active_AD_Bean.class);
                    return active_ad_beans;
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        private HashMap<String, String> getparams() {
            HashMap<String, String> params = new HashMap<>();
            params.put("platform", "2");
            params.put("pos", "1");
            params.put("compare", "65dcae2018c98b3a96f8263d05e3538c");
            return params;
        }

        @Override
        protected void onPostExecute(List<Active_AD_Bean> ad_list) {
            super.onPostExecute(ad_list);
            if (ad_list != null && !ad_list.isEmpty()) {
                for (int i = 0; i < ad_list.size(); i++) {
                    Active_AD_Bean active_ad_bean = (Active_AD_Bean) ad_list.get(i);
                    ImageView img = new ImageView(getActivity());
                    ViewGroup.LayoutParams pamams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                    img.setLayoutParams(pamams);
                    img.setScaleType(ImageView.ScaleType.FIT_XY);
                    ImageLoader.getInstance().displayImage(active_ad_bean.getBimg(), img);
                    views.add(img);
                }
                headAdapter.notifyDataSetChanged();
            }
        }
    }
}
